package yaner.hotel.manager.common.utils;

import yaner.hotel.manager.common.exception.AppException;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * @ClassName DateUtils
 * @Description TODO
 * @Author leigang
 * @Date 2024/5/23-14:10
 * @Version 1.0
 **/
public class DateUtils {


    private static final DateTimeFormatter DATE_FORMAT_YYYY_MM_DD = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final DateTimeFormatter DATE_FORMAT_YYYY_MM_DD01 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 格式化成yyyy-MM-dd格式
     * @param dateStr yyyyMMdd数据
     * @return yyyy-MM-dd格式
     */
    public static String formatDate(String dateStr) {
        if (dateStr == null || dateStr.length() != 8) {
            throw new AppException("Invalid date format: " + dateStr);
        }
        try {
            LocalDate date = LocalDate.parse(dateStr, DATE_FORMAT_YYYY_MM_DD);
            return DATE_FORMAT_YYYY_MM_DD01.format(date);
        } catch (DateTimeParseException e) {
            throw new AppException("Invalid date format: " + dateStr, e);
        }
    }

    /**
     * 生成当前日期，格式为yyyyMMdd
     * @return
     */
    public static String getCurrentDate(){
        LocalDate currentDate = LocalDate.now();
        return currentDate.format(DATE_FORMAT_YYYY_MM_DD);
    }
}
